package com.hua.io.old;

import jdk.nashorn.internal.ir.WhileNode;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author: _hua
 * @created: 2019/3/17.
 * @updater:
 * @description:
 */
public class Server {
    /**
     * 线程和任务比为：n:n 线程池队列貌似没用
     * @param args
     */
    public static void main(String args[]){
        ExecutorService executorService=Executors.newFixedThreadPool(5);
        try {
            ServerSocket serverSocket = new ServerSocket(7700);
            while (true)
            {
                Socket client = serverSocket.accept();
                System.out.println("新增连接："+client.getInetAddress()+":"+client.getPort());
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        handleReq(client);
                    }
                });

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void handleReq(Socket client) {
        System.out.println("处理客户端请求"+client.toString());
        try {
            InputStream inputStream = client.getInputStream();
            while (true){
                byte[] b = new byte[1024];
                int len =inputStream.read(b);
                if(len==-1){
                    continue;
                }
                String msg = new String(b,0,len);
                System.out.println("收到客户端的数据========="+msg);

                OutputStream outputStream=client.getOutputStream();
                outputStream.write(("服务器已收到数据"+msg).getBytes());
                outputStream.flush();
                System.out.println("返回========="+msg);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
